package com.moshme.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.moshme.common.annotation.Log;
import com.moshme.common.constant.FeiJuProject;
import com.moshme.common.core.controller.BaseController;
import com.moshme.common.core.domain.AjaxResult;
import com.moshme.common.core.domain.entity.SysUser;
import com.moshme.common.core.domain.model.LoginUser;
import com.moshme.common.core.page.PageDomain;
import com.moshme.common.core.page.TableDataInfo;
import com.moshme.common.core.page.TableSupport;
import com.moshme.common.enums.BusinessType;
import com.moshme.common.utils.StringUtils;
import com.moshme.project.domain.ProjectStep;
import com.moshme.project.domain.StageConstruct;
import com.moshme.project.service.ProjectStepService;
import com.moshme.project.service.StageConstructService;
import com.moshme.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 望夜
 * @description 施工阶段接口层
 * @date 2023/9/11---9:33
 */
@RestController
@RequestMapping("stageConstruct")
@Api("施工阶段")
public class StageConstructController extends BaseController {

    @Autowired
    ProjectStepService stepService;
    @Autowired
    StageConstructService constructService;
    @Autowired
    ISysUserService userService;

    /**
     * 查询工作日志列表
     * @param stageConstruct
     * @return
     */
    @PreAuthorize("@ss.hasPermi('stage:construct:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询施工阶段工作日志列表")
    public TableDataInfo list(StageConstruct stageConstruct) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        LocalDate[] dateArray = stageConstruct.getDateArray();

        LambdaQueryWrapper<StageConstruct> eq = new LambdaQueryWrapper<StageConstruct>()
                .eq(StageConstruct::getProjectId, stageConstruct.getProjectId())
                .orderByDesc(StageConstruct::getConstructDate);

        if (dateArray != null && dateArray.length >= 2) {
            eq.between(StageConstruct::getConstructDate, dateArray[0], dateArray[1]);
        }

        List<StageConstruct> list = constructService.list(eq);
        list = handleStageConstructs(list);
        int total = list.size();

        List<?> pageList = getPageList(pageDomain, list, total);
        return getDataTable(pageList,total);
    }


    /**
     * 新增施工阶段
     */
    @PreAuthorize("@ss.hasPermi('stage:construct:add')")
    @Log(title = "新增工作日志", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增工作日志")
    public AjaxResult add(@RequestBody @Validated StageConstruct stageConstruct) {
        Long userId = getUserId();
        LambdaQueryWrapper<StageConstruct> eq = new LambdaQueryWrapper<StageConstruct>()
                .eq(StageConstruct::getProjectId, stageConstruct.getProjectId())
                .eq(StageConstruct::getUserId, userId)
                .eq(StageConstruct::getConstructDate, stageConstruct.getConstructDate());

        if (constructService.getOne(eq) != null) {
            return error("您已经在该天添加过工作日志了!");
        }

        LambdaQueryWrapper<ProjectStep> eq1 = new LambdaQueryWrapper<ProjectStep>()
                .eq(ProjectStep::getProjectId, stageConstruct.getProjectId())
                .eq(ProjectStep::getProjectStep, FeiJuProject.SG.getValue());
        ProjectStep projectStep = stepService.getOne(eq1);
        if(StringUtils.isNull(projectStep) || projectStep.getStepStatus() == 0){
            return error("该项目的施工阶段尚未开始，请先阶段预设!");
        }

//        System.out.println("getLoginUser().getUser().getNickName()" + getLoginUser().getUser().getNickName());
        stageConstruct.setUserId(userId);

        return toAjax(constructService.save(stageConstruct));
    }

    /**
     * 修改施工阶段
     */
    @PreAuthorize("@ss.hasPermi('stage:construct:edit')")
    @Log(title = "修改工作日志", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改工作日志")
    public AjaxResult edit(@RequestBody @Validated StageConstruct stageConstruct) {
        LambdaUpdateWrapper<StageConstruct> eq = new LambdaUpdateWrapper<StageConstruct>()
                .eq(StageConstruct::getProjectId, stageConstruct.getProjectId())
                .eq(StageConstruct::getUserId, getUserId())
                .eq(StageConstruct::getConstructDate, stageConstruct.getConstructDate());

//        StageConstruct one = constructService.getOne(eq);
//        if(stageConstruct.getConstructDate() != one.getConstructDate()){
//            return error("只能修改该天的工作日志!");
//        }

        if(StringUtils.isNull(constructService.getOne(eq))){
            return error("请先创建该日工作日志");
        }

        return toAjax(constructService.update(stageConstruct,eq));
    }


    @PreAuthorize("@ss.hasPermi('stage:construct:query')")
    @GetMapping("/{projectId}")
    @ApiOperation(value = "获取工作日志")
    public AjaxResult getWorkLog(@PathVariable Long projectId, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        AjaxResult ajax = AjaxResult.success();
        Long userId = getUserId();

        LambdaQueryWrapper<StageConstruct> eq = new LambdaQueryWrapper<StageConstruct>()
                .eq(StageConstruct::getProjectId, projectId)
                .eq(StageConstruct::getUserId, userId)
                .eq(StageConstruct::getConstructDate, date);

        StageConstruct stageConstruct = constructService.getOne(eq);
        if(StringUtils.isNull(stageConstruct)){
            return error("请先创建该日工作日志");
        }
        ajax.put(AjaxResult.DATA_TAG,stageConstruct);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('stage:construct:remove')")
    @Log(title = "删除工作日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectId}")
    @ApiOperation(value = "删除工作日志")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable Long projectId, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        Long userId = getUserId();

        LambdaQueryWrapper<StageConstruct> eq = new LambdaQueryWrapper<StageConstruct>()
                .eq(StageConstruct::getProjectId, projectId)
                .eq(StageConstruct::getUserId, userId)
                .eq(StageConstruct::getConstructDate, date);

        if(StringUtils.isNull(constructService.getOne(eq))){
            return error("请先创建该日工作日志");
        }

        return toAjax(constructService.remove(eq));
    }


    private List<StageConstruct> handleStageConstructs(List<StageConstruct> list) {
        Map<LocalDate, StageConstruct> tempMap = new LinkedHashMap<>();
        for (StageConstruct construct : list) {
            LocalDate date = construct.getConstructDate();
            String content = construct.getConstructContent();
            String advice = construct.getAdvice();
            Double timeConsume = construct.getTimeConsume();
            Long userId = construct.getUserId();
            SysUser sysUser = userService.selectUserById(userId);
            if (tempMap.containsKey(date)) {
                StageConstruct existingObj = tempMap.get(date);
                if (content != null) {
                    existingObj.setConstructContent(existingObj.getConstructContent() + "，" + content);
                }
                if (advice != null) {
                    existingObj.setAdvice(existingObj.getAdvice() + "，" + advice);
                }
                if (timeConsume != null) {
                    existingObj.setTimeConsume(Double.sum(existingObj.getTimeConsume(), timeConsume));
                    existingObj.setTimeConsumes(existingObj.getTimeConsumes() + "，" + timeConsume);
                }
                if (userId != null && StringUtils.isNotNull(sysUser)) {
                    existingObj.setUserName(existingObj.getUserName() + "，" + sysUser.getNickName());
                }
            } else {
                if(userId != null && StringUtils.isNotNull(sysUser)){
                    construct.setUserName(sysUser.getNickName());
                }
                if( timeConsume != null){
                    construct.setTimeConsumes(String.valueOf(timeConsume));
                }
                tempMap.put(date, construct);
            }
        }

        list = new ArrayList<>(tempMap.values());
        return list;
    }


}
